package com.leyou.auth.service.impl;

import com.leyou.auth.dto.Payload;
import com.leyou.auth.dto.UserDetail;
import com.leyou.auth.service.UserAuthService;
import com.leyou.auth.utils.JwtUtils;
import com.leyou.common.utils.CookieUtils;
import com.leyou.user.client.UserClient;
import com.leyou.user.dto.UserDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Service
public class UserAuthServiceImpl implements UserAuthService {

    @Autowired
    private JwtUtils jwtUtils;

    @Autowired
    private UserClient userClient;

    @Autowired
    private StringRedisTemplate redisTemplate;


    @Override
    public void login(String username, String password, HttpServletResponse response) {

        //查询用户服务的rest接口获取用户信息
        UserDTO userDTO = this.userClient.queryUserByNameAndPass(username, password);

        //把获取到的用户信息转换为UserDetail
        UserDetail userDetail = new UserDetail();
        userDetail.setId(userDTO.getId());
        userDetail.setUsername(userDTO.getUsername());

        //token生成
        String token = jwtUtils.createJwt(userDetail);

        Cookie cookie = new Cookie("LY_TOKEN", token);
        //把cookie绑定给指定的域名
        cookie.setDomain("leyou.com");

        //设置脚本不能访问cookie
        cookie.setHttpOnly(true);

        //从根路径开始匹配
        cookie.setPath("/");

        response.addCookie(cookie);

    }

    @Override
    public void logout(HttpServletRequest request, HttpServletResponse response) {
        try {
            String token = CookieUtils.getCookieValue(request, "LY_TOKEN");

            Payload payload = jwtUtils.parseJwt(token);

            String key = payload.getUserDetail().getUsername();

            //删除redis中内容
            redisTemplate.delete(key);


            deleteCookie(response);

        } catch (Exception e) {
            deleteCookie(response);
        }


    }

    private void deleteCookie(HttpServletResponse response) {
        //删除cookie
        Cookie cookie = new Cookie("LY_TOKEN", "");
        cookie.setDomain("leyou.com");
        cookie.setPath("/");
        cookie.setMaxAge(0);
        response.addCookie(cookie);
    }
}
